import os
import threading
import time
import subprocess
import signal
from datetime import datetime
from typing import List, Dict
from backend.models import ServiceStatus, EmailStats, ProcessedEmail
import json  # 添加json模块
import requests
# 导入日志模块
from backend.utils.logger import write_log

class EmailService:
    """邮件处理服务类 - 纯业务逻辑"""
    
    def __init__(self):
        self.thread = None
        self.running = False
        self.autoemail_module = None
        self.service_start_time = None  # 添加服务启动时间记录
        # 使用内存存储代替文件存储
        self.processed_emails = []
        
    def start_service(self) -> Dict:
        """启动邮件处理服务 - 业务逻辑层"""
        if self.running:
            write_log("INFO", "尝试启动服务，但服务已在运行中")
            return {"message": "服务已在运行中"}
            
        try:
            self.running = True
            self.service_start_time = datetime.now()  # 记录服务启动时间
            write_log("INFO", "服务启动成功")
            # 在新线程中运行邮件处理逻辑
            self.thread = threading.Thread(target=self._run_email_logic)
            self.thread.daemon = True
            self.thread.start()
            return {"message": "服务启动成功"}
        except Exception as e:
            self.running = False
            error_msg = f"启动服务失败: {str(e)}"
            write_log("ERROR", error_msg)
            raise Exception(error_msg)
            
    def stop_service(self) -> Dict:
        """停止邮件处理服务 - 业务逻辑层"""
        if not self.running:
            write_log("INFO", "尝试停止服务，但服务未在运行")
            return {"message": "服务未在运行"}
            
        try:
            self.running = False
            # 通知autoemail模块停止运行
            if self.autoemail_module:
                self.autoemail_module.stop_event.set()
            
            if self.thread and self.thread.is_alive():
                self.thread.join(timeout=5)
            write_log("INFO", "服务已停止")
            return {"message": "服务已停止"}
        except Exception as e:
            error_msg = f"停止服务失败: {str(e)}"
            write_log("ERROR", error_msg)
            raise Exception(error_msg)
            
    def get_service_status(self) -> Dict:
        """获取服务状态 - 业务逻辑层"""
        return {"running": self.running}
        
    def get_statistics(self) -> Dict:
        """获取邮件处理统计信息 - 业务逻辑层"""
        try:
            # 使用内存中的数据而不是文件
            processed_count = len([email for email in self.processed_emails if email.get("status") == "sent"])
            ignored_count = len([email for email in self.processed_emails if email.get("status") == "ignored"])
            failed_count = len([email for email in self.processed_emails if email.get("status") == "failed"])
            
            # 计算成功率
            total_with_result = processed_count + ignored_count + failed_count
            if total_with_result > 0:
                success_rate = round((processed_count / total_with_result) * 100, 1)
            else:
                success_rate = 0.0
            
            # 获取今日处理数量（基于服务启动日期，只统计成功发送的邮件）
            today_count = 0
            if self.service_start_time:
                # 获取服务启动日期
                service_start_date = self.service_start_time.date()
                # 统计今日处理的邮件数量（只统计状态为"sent"的邮件）
                for email_info in self.processed_emails:
                    # 只统计状态为"sent"的邮件
                    if email_info.get("status") == "sent":
                        processed_time_str = email_info.get("processed_time")
                        if processed_time_str:
                            try:
                                processed_time = datetime.fromisoformat(processed_time_str)
                                # 检查处理时间是否在服务启动日期当天
                                if processed_time.date() == service_start_date:
                                    today_count += 1
                            except ValueError:
                                # 如果日期解析失败，跳过该邮件
                                pass
            
            write_log("DEBUG", f"获取统计信息: 总处理数={processed_count}, 今日处理数={today_count}, 成功率={success_rate}%")
            return {
                "total_processed": processed_count,
                "today_processed": today_count,
                "success_rate": success_rate,
                "total_approved": processed_count
            }
        except Exception as e:
            error_msg = f"获取统计信息失败: {str(e)}"
            write_log("ERROR", error_msg)
            raise Exception(error_msg)
            
    def get_processed_emails(self, limit: int = 50) -> List[Dict]:
        """获取已处理的邮件 - 业务逻辑层"""
        try:
            # 使用内存中的数据，按处理时间排序（最新的在前）
            sorted_emails = sorted(
                self.processed_emails, 
                key=lambda x: x.get("processed_time", ""), 
                reverse=True
            )
            # 获取最后limit个邮件
            emails = sorted_emails[:limit] if len(sorted_emails) > limit else sorted_emails
            
            write_log("DEBUG", f"获取已处理邮件列表，数量: {len(emails)}")
            return emails
        except Exception as e:
            error_msg = f"获取已处理邮件失败: {str(e)}"
            write_log("ERROR", error_msg)
            raise Exception(error_msg)
            
    def add_processed_email(self, message_id, sender=None, subject=None, email_date=None, status="processed"):
        """添加已处理的邮件到内存中"""
        email_data = {
            "message_id": message_id,
            "processed_time": datetime.now().isoformat(),
            "sender": sender,
            "subject": subject,
            "email_date": email_date,
            "status": status
        }
        self.processed_emails.append(email_data)
        # 只保留最近1000条记录
        if len(self.processed_emails) > 1000:
            self.processed_emails = self.processed_emails[-1000:]
            
    def _run_email_logic(self):
        """直接运行邮件处理逻辑"""
        try:
            # 导入autoemail模块
            from backend.api import autoemail
            
            # 传递回调函数给autoemail模块，用于保存处理的邮件
            autoemail.set_email_service_callback(self.add_processed_email)
            
            # 保存模块引用，以便停止时使用
            self.autoemail_module = autoemail
            
            # 清除停止事件
            autoemail.stop_event.clear()
            
            write_log("INFO", "开始运行邮件处理逻辑...")
            print("开始运行邮件处理逻辑...")
            
            # 运行邮件监控逻辑，每60秒检查一次#现在我要修改成1800，避免频繁检查邮箱
            autoemail.monitor_emails(1800)    # <-- 直接调用 autoemail.py 中的函数
            
        except Exception as e:
            error_msg = f"运行邮件逻辑时出错: {e}"
            write_log("ERROR", error_msg)
            print(error_msg)
        finally:
            self.running = False
            write_log("INFO", "邮件处理服务已停止")
            print("邮件处理服务已停止")